#include "DeviceList.h"

#include <string.h>
#include <iostream>
using namespace std;

DeviceListNode::DeviceListNode()
{
	device = NULL;
	
}

DeviceListNode::~DeviceListNode()
{

}

DeviceList::DeviceList()
{
	head = NULL;
	pthread_mutex_init(&listMutex, NULL);
}

DeviceList::~DeviceList()
{
	DeviceListNode *tmp = head->next;

	while (tmp != NULL) {
		head->next = tmp->next;
		delete tmp;
		tmp = head->next;
	}
	pthread_mutex_destroy(&listMutex);
}

void DeviceList::lockList()
{
	pthread_mutex_lock(&listMutex);
}

void DeviceList::unlockList()
{
	pthread_mutex_unlock(&listMutex);
}

bool DeviceList::contains(Device *device)
{
	DeviceListNode *node = head;

	while (node != 0) {
		if (strcmp(device->getUDN().c_str(), node->device->getUDN().c_str()) == 0) {
			return true;
		}
		node = node->next;
	}

	return false;
}

void DeviceList::addDevice(Device *device)
{
	DeviceListNode *node = head;
	DeviceListNode *tmp = new DeviceListNode();

	if (head == NULL) {
		tmp->device = device;
		tmp->next = NULL;
		head = tmp;
		return;
	}

	while (node->next != NULL) {
		node = node->next;
	}

	tmp->device = device;
	tmp->next = NULL;

	node->next = tmp;
	cout << "Added " << device->getUDN() << endl;
}

void DeviceList::removeAll()
{
	DeviceListNode *curNode, *next;

	lockList();

	curNode = head;
	head = NULL;

	while (curNode) {
		next = curNode->next;
		delete curNode;
		curNode = next;
	}

	unlockList();
}
